package com.desktop.thread;

import com.desktop.config.FrameConfig;
import com.desktop.entity.Pet;
import com.desktop.frame.MyFrame;
import com.sun.org.apache.xpath.internal.operations.Bool;

import javax.swing.*;
import java.awt.*;

/**
 * @author 粥灰灰
 * @created 2022/2/3
 * @version 1.0
 * @Description 调用逐帧画面，实现动画效果的线程
 */
public class MyThread {

    private String prefix = null;
    private String suffix = null;
    private int start = 0;
    private int now = 0;
    private int end = 0;
    private boolean interruptFlag = true;
    private Thread dynamicPet = null;
    private MyFrame myFrame = null;


    public MyThread() {

    }


    public MyThread(MyFrame myFrame, Pet pet) {
        this.prefix = pet.getPrefix();
        this.suffix = pet.getFileType();
        Runnable impl = null;
        boolean ram = myFrame.isUseRam();//先判断是否为内存加载模式
        if (ram)
            impl = new UseRam();
        else
            impl = new UseCpu();
        this.dynamicPet = new Thread(impl);
        this.dynamicPet.setName(pet.getPetName());
        this.myFrame = myFrame;
    }


    public void start() {
        interruptFlag = true;
        dynamicPet.start();
    }

    public void interrupt() {
        interruptFlag = false;
        dynamicPet.interrupt();
    }


    /**
     * @author 粥灰灰
     * @created 2022/3/16
     * @version 1.0
     * @Description 每次只加载一张图片进内存，节省内存资源
     */
    class UseCpu implements Runnable {
        @Override
        public void run() {
            try {
                int i = 0;
                JLabel jLabel = myFrame.getjLabel();
                String[] imagePaths = myFrame.getImagePaths();
                while (interruptFlag) {
                    Thread.sleep(40);
                    ImageIcon icon = new ImageIcon(imagePaths[i++]);
                    icon.setImage(icon.getImage().getScaledInstance(myFrame.getPetWidth(),myFrame.getPetHeight(), Image.SCALE_AREA_AVERAGING));
                    MyFrame.displayPet(jLabel, icon);
                    if (i >= imagePaths.length) {
                        i = 0;
                    }
                }
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
        }
    }

    /**
     * @author 粥灰灰
     * @created 2022/3/16
     * @version 1.0
     * @Description 使用一次性加入内存的全部图片，免去多次反复的I/O操作
     */
    class UseRam implements Runnable {
        @Override
        public void run() {
            try {
                int i = 0;
                JLabel jLabel = myFrame.getjLabel();
                ImageIcon[] imageIcons = myFrame.getImageIcons();
                while (interruptFlag) {
                    Thread.sleep(40);
                    MyFrame.displayPet(jLabel, imageIcons[i++]);
                    if (i >= imageIcons.length) {
                        i = 0;
                    }
                }
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
        }
    }
}
